package com.felix.collection.completion;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
 * Renderer
 *
 * @author xjh
 * @version 1.0
 * @date 2019-03-28
 */
public class Renderer {

    private final ExecutorService executorService;

    public Renderer(ExecutorService executorService) {
        this.executorService = executorService;
    }

    void renderPage(CharSequence source) {
        List<String> info = scanForImageInfo(source);
        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
        info.forEach(e -> {
            completionService.submit(() -> "xjh");
        });
        try {
            for (int i = 0, n = info.size(); i < n; i++) {
                Future<String> f = completionService.take();
                String value = f.get();
                System.out.println(value);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private List<String> scanForImageInfo(CharSequence source) {
        return Lists.newArrayList();
    }

    String renderPageWithAd() throws InterruptedException {
        long endNanos = System.nanoTime();
        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
        Future<String> f = completionService.submit(() -> "xjh");
        String ad;
        try {
            long timeLeft = endNanos - System.nanoTime();
            ad = f.get(timeLeft, NANOSECONDS);
        } catch (ExecutionException e) {
            ad = "xjh";
        } catch (TimeoutException e) {
            ad = "xjh";
            f.cancel(true);
        }
        return ad;
    }
}
